package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.MenuDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Menu;
import com.itheima.health.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName CheckItemServiceImpl
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/8/20 16:00
 * @Version V1.0
 */
// dubbo（整合声明式事务处理1：配置applicationContext-tx.xml对类代理，2：@Service(interfaceClass = CheckItemService.class)）
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuDao menuDao;

    @Override
    public List<Menu> findMenuListByUsername(String username) {
        List<Menu> menus = menuDao.findMenuListByUsername(username);

        //创建父菜单集合
        List<Menu> parentMenus = new ArrayList<>();
        //创建子菜单集合
        List<Menu> childrenMenus = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getLevel() == 1) {
                parentMenus.add(menu);
            }
            if (menu.getLevel() == 2) {
                childrenMenus.add(menu);
            }
        }

        //将子菜单添加到相关联的父菜单中
        for (Menu parentMenu : parentMenus) {
            List<Menu> list = new ArrayList<>();
            for (Menu childrenMenu : childrenMenus) {
                if (childrenMenu.getParentMenuId().equals(parentMenu.getId())) {
                    list.add(childrenMenu);
                }
            }
            parentMenu.setChildren(list);
        }
        return parentMenus;
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //分页查询，使用mybatis的分页助手插件实现分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Menu> page = menuDao.findPage(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(), page.getResult());
    }

    //新增菜单
    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    //删除菜单
    @Override
    public void delete(Integer id) {
        menuDao.delete(id);
    }

    //编辑菜单数据回显
    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    //编辑菜单
    @Override
    public void updateMenu(Menu menu) {

        menuDao.updateMenu(menu);
    }

    //查询所有菜单
    @Override
    public List<Menu> findAll() {

        return menuDao.findAll();
    }


}
